package com.xianyun.smartpicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xianyun.smartpicturebackend.annotation.AuthCheck;
import com.xianyun.smartpicturebackend.common.BaseResponse;
import com.xianyun.smartpicturebackend.common.DeleteRequest;
import com.xianyun.smartpicturebackend.common.PageRequest;
import com.xianyun.smartpicturebackend.common.ResultUtils;
import com.xianyun.smartpicturebackend.constant.UserConstant;
import com.xianyun.smartpicturebackend.exception.BusinessException;
import com.xianyun.smartpicturebackend.exception.ErrorCode;
import com.xianyun.smartpicturebackend.exception.ThrowUtils;
import com.xianyun.smartpicturebackend.model.dto.user.*;
import com.xianyun.smartpicturebackend.model.entity.User;
import com.xianyun.smartpicturebackend.model.vo.UserLoginVO;
import com.xianyun.smartpicturebackend.model.vo.UserVO;
import com.xianyun.smartpicturebackend.service.UserService;
import io.github.classgraph.utils.LogNode;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author xianYun
 * @version 1.0
 **/

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public BaseResponse<String> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        long userId = userService.userRegister(userRegisterRequest);
        return ResultUtils.success("ok");
    }

    /**
     * 用户登录
     * @param userLoginRequest 自定义请求类
     * @param request
     * @return 给前端返回脱敏后的用户信息
     */
    @PostMapping("/login")
    public BaseResponse<UserLoginVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        UserLoginVO userLoginVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userLoginVO);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean b = userService.userLogout(request);
        return ResultUtils.success(b);
    }

    /**
     * 根据当前请求，返回脱敏后的用户信息
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<UserLoginVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        //脱敏用户信息
        UserLoginVO loginUserVO = userService.getLoginUserVO(loginUser);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 提供给管理员使用，返回用户的全部信息（不脱敏）
     * @param userId
     * @return
     */
    @GetMapping("/get/use")
    public BaseResponse<User> getUserById(Long userId) {
        ThrowUtils.throwIf(ObjUtil.isNull(userId), ErrorCode.PARAMS_ERROR);
        User user = userService.getById(userId);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 普通用户查询用户，返回脱敏后的用户信息
     * @param userId
     * @return
     */
    @GetMapping("/get/useVO")
    public BaseResponse<UserVO> getUserVOById(Long userId) {
        ThrowUtils.throwIf(ObjUtil.isNull(userId), ErrorCode.PARAMS_ERROR);
        User user = userService.getById(userId);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 创建用户
     * @param
     * @return
     */
    @PostMapping("/addUser")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        User user = new User();
        //将userAddRequest中的属性拷贝到user中
        BeanUtil.copyProperties(userAddRequest, user);
        //给用户设置默认密码
        final String DEFAULT_USER_PASSWORD = "123456";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_USER_PASSWORD);
        user.setUserPassword(encryptPassword);
        //插入数据库
        boolean save = userService.save(user);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    @PostMapping("/delete/byId")
    public BaseResponse<Boolean> deleteUserById(@RequestBody DeleteRequest deleteRequest) {
        if(deleteRequest == null || deleteRequest.getId() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean del = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!del, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(del);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if(userUpdateRequest == null || userUpdateRequest.getId() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest, user);
        boolean update = userService.updateById(user);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(update);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long pageNum = userQueryRequest.getPageNum();//当前页
        long pageSize = userQueryRequest.getPageSize();//每页显示多少条
        //使用mybatisplus 自带的分页查询，完成分页，
            /*
            1. 需要构建一个分页对象，需要指定当前页，页面大小
            2. 指定查询条件
             */
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        ThrowUtils.throwIf(ObjUtil.isNull(userPage), ErrorCode.NOT_FOUND_ERROR,"返回的分页数据为空");
        //创建一个脱敏后的分页对象
        Page<UserVO> userVOPage = new Page<>(pageNum, pageSize, userPage.getTotal());
        //userPage.getRecords() 查询后返回的分页数据，数据类型是List<User>
        //将查询到的分页数据进行脱敏，复制给脱敏后的分页对象
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        //将脱敏后的数据，放进对应的分页对象中
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

}
